package com.scientific.research.gobang.service.submitlist.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scientific.research.gobang.mapper.SubmitListMapper;
import com.scientific.research.gobang.pojo.SubmitList;
import com.scientific.research.gobang.pojo.User;
import com.scientific.research.gobang.service.SubmitListService;
import com.scientific.research.gobang.service.UserService;
import com.scientific.research.gobang.utils.RedisUtil;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SubmitListServiceImpl implements SubmitListService {
    @Autowired
    SubmitListMapper submitListMapper;
    @Autowired
    UserService userService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    RedissonClient redissonClient;

    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    @Override
    public int GetRunCodeNum(Map map, HttpServletRequest request) {
        User user = userService.LodeUserMessage(map);
        return (int) redisUtil.get(user.getEmail() + "_runCode");
    }

    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    @Override
    public List<Object> GetSubmitList(Map map) {
        User user = userService.LodeUserMessage(map);
        List list = (List) redisUtil.get(user.getEmail() + "_submitList");

        if (list == null) {//如果从Redis缓存中无法读取到数据，就从数据库中查询
            RLock lock = redissonClient.getLock(user.getEmail() + "_submitList");
            lock.lock(15, TimeUnit.SECONDS);// Redisson分布式锁,防止缓存击穿

            list = (List) redisUtil.get(user.getEmail() + "_submitList");// 再从Redis获取一次，如果没获取到就从数据库查
            if (list == null) {
                QueryWrapper<SubmitList> mapper = new QueryWrapper<>();
                mapper.orderByDesc("id");
                mapper.eq("email", user.getEmail());
                list = submitListMapper.selectObjs(mapper);
                //将查询结果放入Redis缓存中，以后查询就可以从缓存中读取
                redisUtil.set(user.getEmail() + "_submitList", list);
                //解锁
                lock.unlock();
            }
        }
        return list;
    }
}
